<script setup lang="ts">
import {ref, PropType, nextTick, onBeforeMount} from 'vue'
import {ElTree, ElMessage} from 'element-plus'
import {HelpView, gethealthGuideTreeList, saveIdentificationInfor, SaveInfor} from '@/api/medicalExaminerDesk/constitutionIdentify'
import dDialog from '@/components/dDialog/dDialog.vue'
//是否显示
const props = defineProps({
  //显示
  showDialog:{
    type:Boolean,
    required:true
  },
  guideDeatil: {
    type: Array as PropType<Array<string>>,
    required: true
  },
  result:{
    type: String,
    required: true
  },
  saveInfo:{
    type: Object as PropType<SaveInfor>,
    required: true
  },
  register:{
    type: Number,
    required: true
  }
})

const emits = defineEmits(['close'])
const formData = ref(props.saveInfo)
// 显示加载状态
const showSaveLoading = ref(false)
//选中
const hasSeleted = ref(false)

//菜单树数据
const guideTreeData = ref<Array<HelpView>>()
const allSeleteData = ref<Array<string>>([])

//按钮值映射
const guideTreeProps = {
  children: 'children',
  label: 'label',
  disabled: 'disabled',
  id:'id'
}

const guideTreeRef = ref<InstanceType<typeof ElTree>>()

//设置勾选数据
const setGuideTreeSelete = () => {
  guideTreeRef.value?.setCheckedKeys(props.guideDeatil.length ? props.guideDeatil : allSeleteData.value)
  console.log(allSeleteData.value)
  hasSeleted.value = props.guideDeatil.length > 0 || allSeleteData.value.length > 0 ? true : false
}

//获取勾选数据
const getGuideTreeSelete = (): Array<string> | undefined => {
  return guideTreeRef.value?.getCheckedKeys(true) as
    | Array<string>
    | undefined
}

//更新选中信息
const updateSelete = () => {
  const data = getGuideTreeSelete()
  allSeleteData.value = data ? data : []
}

//详细数据
const setGuideDetail = () => {
  setGuideTreeSelete()
  nextTick(() => {
    updateSelete()
  })
}

//获取菜单树
const getTreeData = () => {
  const typeList = props.result ? props.result.split('、') : []
  if (props.register > 2) {
    const treeData:Array<HelpView> = props.saveInfo.constitution ? JSON.parse(props.saveInfo.constitution) : []
    const treeShowData:Array<HelpView> = []
    treeData.map((item) => {
      const itemTree:HelpView = {label:item.label, children:[], disabled:true, id:item.id}
      item.children?.map((ite) => {
        const iteTree:HelpView = {label:ite.label, children:[], disabled:true, id:ite.id}
        ite.children?.map((its) => {
          iteTree.children?.push({label:its.label, children:[], disabled:true, id:its.id})
        })
        itemTree.children?.push(iteTree)
      })
      treeShowData.push(itemTree)
    })
    guideTreeData.value = treeShowData
    nextTick().then(() => {
      setGuideDetail()
    })
  } else {
    //获取树形结构
    gethealthGuideTreeList().then((res) => {
      const {data} = res.data
      const treeData:Array<HelpView> = []
      data.map((item) => {
        const itemTree:HelpView = {label:'', children:[], disabled:props.register > 2 ? true : false, id:item.id}
        itemTree.label = item.name
        const type = item.name.split('-')
        const ispush = typeList.filter((items) => items === type[1])
        item.smallTypeList.map((ite) => {
          const iteTree:HelpView = {label:'', children:[], disabled:props.register > 2 ? true : false, id:ite.id}
          iteTree.label = ite.smallTypeName
          ite.healthContentList.map((its) => {
            iteTree.children?.push({label:its.healthValue, disabled:props.register > 2 ? true : false, id:its.id})
            if (ispush.length && !props.guideDeatil.length && !props.saveInfo.constitution)allSeleteData.value.push(its.id)
          })
          itemTree.children?.push(iteTree)
        })
        treeData.push(itemTree)
      })
      guideTreeData.value = treeData
      setGuideDetail()
    })
  }
}

//选中变更
const onChange = (_data: HelpView, obj: {checkedKeys: string[]}) => {
  hasSeleted.value = obj.checkedKeys.length ? true : false
  updateSelete()
}

const getPdfData = () => {
  const treeData:Array<HelpView> = []
  guideTreeData.value?.map((item) => {
    const itemTree:HelpView = {label:item.label, children:[], version:'1.0.0', id:item.id}
    item.children?.map((ite) => {
      const iteTree:HelpView = {label:ite.label, children:[], id:ite.id}
      ite.children?.map((its) => {
        if (allSeleteData.value.filter((ites) => ites === its.id).length)iteTree.children?.push({label:its.label, id:its.id})
      })
      if (iteTree.children?.length)itemTree.children?.push(iteTree)
    })
    if (itemTree.children?.length)treeData.push(itemTree)
  })
  return treeData
}

// 确认按钮
const onConfirm = () => {
  formData.value.constitution = JSON.stringify(getPdfData())
  formData.value.guideValue = JSON.stringify(allSeleteData.value)
  showSaveLoading.value = true
  saveIdentificationInfor(formData.value).then(() => {
    showSaveLoading.value = false
    ElMessage.success('保存成功')
    emits('close')
  }).catch((error) => {
    showSaveLoading.value = false
    console.warn(error)
  })
}

//关闭
const onClose = () => {
  emits('close')
}

//取消按钮
const onCancel = () => {
  onClose()
}

onBeforeMount(() => {
  getTreeData()
})
</script>

<template>
  <d-dialog
    title="选择健教指导"
    custom-class="selete"
    :show-dialog="showDialog"
    :show-save-loading="showSaveLoading"
    :cancel-text="props.register>2?'关闭':'取消'"
    :hide-save-btn="props.register>2"
    @cancel="onCancel"
    @confirm="onConfirm"
    @close="onClose"
  >
    <div>
      <el-scrollbar
        class="d-common-flex-full d-common-post-rel rolemangaer-tree__wapper"
        wrap-class="d-common-width-full d-common-post-abs"
        :style="{height:'400px',width:'560px'}"
      >
        <el-tree
          ref="guideTreeRef"
          class="d-common-width-full guideTree"
          node-key="id"
          show-checkbox
          highlight-current
          default-expand-all
          :data="guideTreeData"
          :props="guideTreeProps"
          @check="onChange"
        >
          <template #default="{ node }">
            <span class="custom-tree-node">
              {{ node.label }}
            </span>
          </template>
        </el-tree>
      </el-scrollbar>
      <div :style="{height:'1px',borderTop:'1px solid #ccc',paddingBottom:'20px',width:'100%'}" />
      <el-input v-model="formData.guideWriteValue" type="textarea" placeholder="请输入健教指导" maxlength="2000" :show-word-limit="true" :disabled="props.register>2?true:false" />
    </div>
  </d-dialog>
</template>

<style lang="less" scoped>
.guideTree{
  :deep(.el-tree-node__content){
    height: auto;
    align-items: flex-start;
  }
 :deep(.el-checkbox){
    height: 24px;
  }
}

</style>
<style scoped>
.rolemangaer-tree__wapper {
  height: var(--rolemangaer-tree-height);
  padding: 0;
  margin: 18px 23px;
}

.custom-tree-node {
  white-space:normal;
  width:'400px';
  overflow:'hidden';
  word-wrap: 'normal';
  height: auto;
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
<style>
.selete{
  width: 660px;
}
</style>